package com.sci.web.service.common;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.sci.config.MyConstants;
import com.sci.web.business.admin.SysEnumsBusiness;
import com.sci.web.dao.FileUploadfileinfDao;
import com.sci.web.model.dto.FullAvatarDto;
import com.sci.web.model.genmodel.FileUploadfileinf;
import com.sci.web.model.genmodel.User;
import com.sci.web.util.DateUtil;
import com.sci.web.util.GetWaterId;
import com.sci.web.util.ImageUtil;
import com.sci.web.util.PicUtils;
import com.sci.web.util.StringUtil;

public class FileClientService {
	
	
	
	public SysEnumsBusiness sysEnumsBusiness= new SysEnumsBusiness();
	
	public String uploadFile(UploadFile uploadFile , User user , String rootPath){
		
		String result = null;
		
		
		String fileWebName = sysEnumsBusiness.getSysEnumsByKeyToValue("fileWebName");
		if(StringUtil.isEmpty(fileWebName)){
			return null;
		}
		try {
			File readFile = uploadFile.getFile();
			//tomcat-->web 之前的路径
			String substring = rootPath.substring(0, rootPath.indexOf("lexy_blog"));
			//web 之后的路径
			String currDatatTime = DateUtil.getCurrDatatTime(DateUtil.DATA_FORMAT_2);
			String dicPath = MyConstants.FILE_PATH_ADMIN+currDatatTime;
			String realDicPath = substring + fileWebName+File.separator+ dicPath;
			System.out.println(realDicPath);
			
			File file = new File(realDicPath);
			if(!file.exists()){
				file.mkdirs();
			}
			
			String name = readFile.getName();
			String expandName = name.split("\\.")[1];
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			String saveName = uuid + "."+ expandName;
			String uploadPath = realDicPath+File.separator+saveName;
			//File realUploadFile =realFile;
			//判断是不是图片
			String picType = PicUtils.getPicType(new FileInputStream(readFile));
			readFile.renameTo(new File(uploadPath));
			
			FileUploadfileinf fu = new FileUploadfileinf();
			String relativePath = dicPath+File.separator+saveName;
			fu.setFilePath(relativePath);
			if(!"unknown".equals(picType)){
				
				
				String cutImage = this.cutImage(uploadPath, 0.875, substring+fileWebName);
				String thumbDicPath = substring  + fileWebName+File.separator+MyConstants.FILE_PATH_ADMIN_THUMB+currDatatTime;
				File thumbFile = new File(thumbDicPath);
				if(!thumbFile.exists()){
					thumbFile.mkdirs();
				}
				String thumbRealPath = thumbDicPath+File.separator+"thumb_"+saveName;
				String relativePath_thumb =MyConstants.FILE_PATH_ADMIN_THUMB+currDatatTime+File.separator+"thumb_"+saveName;
				ImageUtil.zoomImageScale(cutImage, thumbRealPath, 250, 286);
				fu.setThumbPath(relativePath_thumb);
			}
			fu.setFdirectory(currDatatTime);
			fu.setExpandName(expandName);
			fu.setFileShowName(name);
			fu.setFileName(saveName);
			fu.setRelateId("---");
			fu.setNotePersion(user.getUserNo());
			fu.setWebName(user.getUserName());
			fu.setId(GetWaterId.getWaterId("_Upload_"));
			fu.setModeId("admin");
			fu.setClassId("diy");
			FileUploadfileinfDao.me.insertFileUploadfileinf(fu);
			result = fu.getId();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	
	public String cutImage(String source , double widthDivideHeight  , String fileWebName ){
		
			File file = new File(source);
	        BufferedImage bufferedImage;
			try {
				bufferedImage = ImageIO.read(file);
				 if (null == bufferedImage)  return null;
			        int originalWidth = bufferedImage.getWidth();
			        int originalHeight = bufferedImage.getHeight();
			        int originalWidthHalf = originalWidth/2;
			        int originalHeightHalf = originalHeight/2;
			        int newWidth = 0;
			        int newHeight = 0;
			        if(originalWidth<originalHeight){
			        	newWidth = originalWidth;
			        	newHeight =new BigDecimal((double)originalWidth/widthDivideHeight).setScale(0, BigDecimal.ROUND_HALF_UP).intValue()  ;
			        }else{
			        	newWidth = new BigDecimal((double)originalHeight*widthDivideHeight).setScale(0, BigDecimal.ROUND_HALF_UP).intValue() ;
			        	newHeight = originalHeight;
			        }
			        int newWidthHalf = newWidth/2;
			        int newHeightHalf = newHeight/2;
			        System.out.println(newWidth+"---"+newHeight);
			        
			        int x = originalWidthHalf-newWidthHalf;
					int y = originalHeightHalf-newHeightHalf;
					String cutpath =  fileWebName+File.separator+MyConstants.FILE_PATH_ADMIN_CUT;
					
					File newFile = new File(cutpath);
					if(!newFile.exists()){
						newFile.mkdirs();
					}
			       return  ImageUtil.cutImage(file, cutpath, x, 0, newWidth, newHeight);
			} catch (Exception e) {
				e.printStackTrace();
			}
	       return null;
		
	}
	
	
	
	
	
	public List<Map<String , String>> getFileList(String uploadType){
		
		List<Map<String , String>> mapList = new ArrayList<Map<String,String>>();
		List<FileUploadfileinf> fileAll = FileUploadfileinfDao.me.geetFileUploadfileinfAll();
		if(fileAll!=null && fileAll.size()>0){
			for (FileUploadfileinf fu : fileAll) {
				Map<String , String> map = new HashMap<String, String>();
				map.put("showName", fu.getFileShowName());
				String filePath = "";
				String filePathThumb = "";
				if("admin".equals(uploadType)){
					filePath = MyConstants.FILE_PATH_ADMIN+fu.getFdirectory()+File.separator+fu.getFileName();
					if(MyConstants.PIC_SUFFIX.indexOf(fu.getExpandName().toLowerCase())>-1){
						filePathThumb = MyConstants.FILE_PATH_ADMIN_THUMB+fu.getFdirectory()+File.separator+fu.getFileName();
					}
				}
				map.put("filePath", filePath);
				map.put("filePathThumb", filePathThumb);
				mapList.add(map);
			}
		}
		return mapList;
	}
	
	
	
	
	
	
	
	public FullAvatarDto uploadFullAvatar(HttpServletRequest request , String rootPath){
		 FullAvatarDto result = new FullAvatarDto();
		 result.avatarUrls = new ArrayList();
		 result.success = false;
		 result.msg = "Failure!";
		 String fileName = UUID.randomUUID().toString().replaceAll("-", "");
		 
		 
		 //定义一个变量用以储存当前头像的序号
		 int avatarNumber = 1;
		 try {
			 
			 FileItemFactory factory = new DiskFileItemFactory();
			 ServletFileUpload upload = new ServletFileUpload(factory);
			 FileItemIterator fileItems = upload.getItemIterator(request);

			 //基于原图的初始化参数
			 String initParams = "";
			 BufferedInputStream	inputStream;
			 BufferedOutputStream outputStream;
			 //遍历所有文件域
			 
			 
			 while(fileItems.hasNext() ){
				 
	    		FileItemStream fileItem = fileItems.next();
		   		String fieldName = fileItem.getFieldName();
		   		//是否是原始图片 file 域的名称（默认的 file 域的名称是__source，可在插件配置参数中自定义。参数名：src_field_name）
		   		Boolean isSourcePic = fieldName.equals("__source");
		   		//文件名，如果是本地或网络图片为原始文件名（不含扩展名）、如果是摄像头拍照则为 *FromWebcam
		   		//String name = fileItem.getName();
		   		//当前头像基于原图的初始化参数（即只有上传原图时才会发送该数据），用于修改头像时保证界面的视图跟保存头像时一致，提升用户体验度。
		   		//修改头像时设置默认加载的原图url为当前原图url+该参数即可，可直接附加到原图url中储存，不影响图片呈现。
		   		if ( fieldName.equals("__initParams") ){
		   			inputStream = new BufferedInputStream(fileItem.openStream());
		   			byte[] bytes = new byte [inputStream.available()];
		   			inputStream.read(bytes);
		   			initParams = new String(bytes, "UTF-8");
		   			inputStream.close();
		   		}
		   		//如果是原始图片 file 域的名称或者以默认的头像域名称的部分“__avatar”打头
		   		else if ( isSourcePic || fieldName.startsWith("__avatar") ){
		   			String virtualPath = MyConstants.FILE_PATH_FULLAVATAR+"jsp_avatar" + avatarNumber + "_" + fileName + ".jpg";
		   			//原始图片（默认的 file 域的名称是__source，可在插件配置参数中自定义。参数名：src_field_name）。
		   			if( isSourcePic ){
		   				result.sourceUrl = virtualPath = MyConstants.FILE_PATH_FULLAVATAR+"jsp_source_" + fileName + ".jpg";
		   			}
		   			//头像图片（默认的 file 域的名称：__avatar1,2,3...，可在插件配置参数中自定义，参数名：avatar_field_names）。
		   			else{
		   				result.avatarUrls.add(virtualPath);
		   				avatarNumber++;
		   			}
	   				inputStream = new BufferedInputStream(fileItem.openStream());
	   				String filePath = rootPath + virtualPath.replace("/", "\\");
	   				
	   				//创建文件夹
	   				this.createDirtory(rootPath+MyConstants.FILE_PATH_FULLAVATAR);
	   				MyConstants.log.info("====>filePath:"+filePath);
					outputStream = new BufferedOutputStream(new FileOutputStream(filePath));
					Streams.copy(inputStream, outputStream, true);
					inputStream.close();
					outputStream.flush();
					outputStream.close();
					result.success = true;
			        result.msg = "Success!";
					
		   		}
			 }
		} catch (Exception e) {
			e.printStackTrace();
		}
        return result;
	}
	
	
	
	
	public void createDirtory(String path){
		
		System.out.println("====>"+path);
		File file = new File(path);
		if(!file.exists()){
			file.mkdirs();
		}
	}
	
	
	
	public Page<FileUploadfileinf> getFileUploadfileinfPageInate(int pageNumber , int pageSize , String searchStr , String notePerson){
		return FileUploadfileinfDao.me.geetFileUploadfileinfPageInate(pageNumber, pageSize, searchStr, notePerson);
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public static void main(String[] args) {
		String dd = "4564564564564ggg12313213";
		
		System.out.println(dd.substring(0,dd.indexOf("ggg")));
		
	}

}
